//路由鉴权
import router from '@/router'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
nprogress.configure({ showPinner: false })
import pinia from './stores/index'
import { useUserStore } from './stores/modules/userStore'
const userStore = useUserStore(pinia)

//全局前置守卫
router.beforeEach(async (to, from, next) => {
  document.title = `硅谷甄选-` + to.meta.title
  nprogress.start()
  let token = userStore.token
  let username = userStore.username

  if (token) {
    if (to.path === '/login') {
      next({ path: '/' })
    } else {
      if (username) {
        next()
      } else {
        try {
          // 发起请求获取用户信息
          await userStore.getUser()
          // 确保异步操作完成后再进行路由跳转
          next()
        } catch (error) {
          await userStore.loginOut()
          next({ path: '/login', query: { redirect: to.path } })
        }
      }
    }
  } else {
    if (to.path === '/login') {
      next()
    } else {
      next({ path: '/login', query: { redirect: to.path } })
    }
  }
})

//全局后置守卫
router.afterEach((to: any, from: any) => {
  nprogress.done()
})
